#include"usermodel.hpp"
#include"ConnectionPool.h"
#include<iostream>
using namespace std;


// user 表的增加方法
bool UserModel::insert(User &user)
{
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql,"insert into User(name,password,state) values('%s','%s','%s')",
        user.getName().c_str(),user.getPwd().c_str(),user.getState().c_str());

    ConnectionPool *cp = ConnectionPool::getConnectionPool();
    shared_ptr<Connection> sp = cp->getConnection();

    if(sp->update(sql))
    {
        // 获取插入成功的用户数据生成的主键
        user.setId(mysql_insert_id(sp->getConnection()));
        return true;
    }

    return false;
}

// 根据用户号码查询用户信息
User UserModel::query(int id)
{
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql,"select * from User where id = %d",id);

    ConnectionPool *cp = ConnectionPool::getConnectionPool();
    shared_ptr<Connection> sp = cp->getConnection();

    MYSQL_RES *res = sp->query(sql);
    if(res != nullptr) {
        // 获取返回值的行
        MYSQL_ROW row = mysql_fetch_row(res);
        if(row != nullptr)
        {
            User user;
            user.setId(atoi(row[0]));
            user.setName(row[1]);
            user.setPwd(row[2]);
            user.setState(row[3]);
            // 这里一定要释放资源
            mysql_free_result(res);
            return user;
        }
    }

    return User();
}

bool UserModel::updateState(User &user)
{
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql,"update User set state = '%s' where id = '%d'",user.getState().c_str(),user.getId());

    ConnectionPool *cp = ConnectionPool::getConnectionPool();
    shared_ptr<Connection> sp = cp->getConnection();

    if(sp->update(sql))
    {
        
        return true;
    }

    return false;
}

void UserModel::resetState()
{
    // 组装sql语句
    char sql[1024] = "update User set state='offline' where state='online'";

    ConnectionPool *cp = ConnectionPool::getConnectionPool();
    shared_ptr<Connection> sp = cp->getConnection();

    sp->update(sql);
}
